package com.cnpc.framework.interceptor;

import com.google.gson.Gson;
import com.lc.service.AppService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class AjaxControlInterceptor extends HandlerInterceptorAdapter {


	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	AppService appService;

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {


		try{
			String requestURI = request.getRequestURI();
			logger.error("requestURI:"+requestURI);
			String ip = getIpAddr(request);
			logger.error("ip:"+ip);

			String method = request.getMethod();
			String contentType = request.getContentType();

			logger.error("method:" + method+"/" + contentType);
			String queryString = request.getQueryString();
			logger.error("queryString:" + queryString);
			Map parameterMap = request.getParameterMap();
			logger.error("parameterMap:" + new Gson().toJson(parameterMap));
		}catch (Exception e){
			e.printStackTrace();
		}

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT");
		response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
		response.setHeader("Max-Age", "3600");
		return true;
	}

	public static String getIpAddr(HttpServletRequest request) throws Exception {
		String ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("PRoxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
